package com.easy.core.web.controller;

import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.easy.core.dbHandle.CommonService;

public class BasicController {
	
	private   PrintWriter			out;
	
	protected Logger 				log 		= 		Logger.getLogger(this.getClass());
	protected HttpSession			session;
	protected HttpServletRequest 	request;
	protected HttpServletResponse 	response;
	
	@Resource(name="commonService")
	protected CommonService			commonService;
	
	protected void setOutHead() {
		this.response.setCharacterEncoding("utf-8");
		this.response.setContentType("text/html; charset=utf-8");
		this.response.setHeader("Cache-Control", "no-cache");	//HTTP 1.1
		this.response.setHeader("Pragma", "No-cache");			//HTTP 1.0
		this.response.setHeader("Expires", "0");				//prevents caching at the proxy server
	}
	
	protected PrintWriter getOut() {
		try{
			if(null == this.response) { return null;}
			if(null != out) { return out; }
			setOutHead();
			out = this.response.getWriter();
		} catch (Exception e) {
			log.error(e);
		}
		return out;
	}
	
	public String result(boolean b, String description) {
		JSONObject obj = new JSONObject();
		try{
			obj.put("b", b);
			obj.put("desc", description);
		} catch (JSONException e) { 
			return "{\"b\":\"false\",\"desc\":\"\"}";
		}
		return obj.toString();
	}

	protected void closeOut(){
		if(null!=out){
			out.flush();
			out.close();
		}
	}
	
	public CommonService getCommonService() {
		return commonService;
	}

	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}
}
